import { Block, View, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import withWeapp from '@tarojs/with-weapp'
const AV = require('../../libs/av-weapp-min.js')
AV.init({
  appId: 'FuEKBAKt7fr6CnVTfMVXKyMm-gzGzoHsz',
  appKey: '9Gw1lGPn1fgxJ3gKw04BltIU',
  serverURLs: 'https://fuekbakt.lc-cn-n1-shared.com'
}) //上面是访问数据库接口 商业版

import * as echarts from '../../ec-canvas/echarts.js'
import EcCanvas from '../../ec-canvas/ec-canvas'
import Select2 from '../../Componet/select2/select2'
import Select from '../../Componet/select/select'
import './index.scss'
const app = Taro.getApp()

//声明需要用到的全局变量
var chart = null
var x = [] //折线图横轴坐标
var y1 = [] //折线图纵轴坐标1
var y2 = [] //折线图纵轴坐标2
var glodata = [] //存放访问接口返回的数组，即暂存折线图的所有数据，方便修改
var the_newest = ''
var area = '中国'
var type = 'confirmedCount'
var glo_city_list = [] //存放某省的城市列表
var glo_data_detail = [] //存放数据明细表格的数据

//先调用一次函数，但是什么也没做
var paramsJson = {
  event_name: '2019-nCoV',
  area_name: '中国',
  type_list: ['confirmedCount']
  // start: '2020-1-29',
  // end: '2020-1-31'
}
AV.Cloud.run('get_stat_data', paramsJson).then(
  function(data_list) {},
  function(err) {}
) //接口函数1，用于获取折线图数据，具体使用参照接口文档

var city_name = { event_name: '2019-nCoV', area_name: ' ' }
AV.Cloud.run('get_areas', city_name).then(
  function(name_list) {},
  function(err) {}
) //接口函数2，用于获取某省的城市列表，具体使用参照接口文档

//折线图初始化函数，但是数据还没录入
function initChart(canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height
  })
  canvas.setChart(chart)
  //下面这个是表格数据
  var option = {
    title: {
      left: 'right'
    },
    animation: false,
    color: ['#778899', '#37A2DA'],
    legend: {
      data: ['总数', '新增'],
      top: 20,
      left: 'right',
      z: 100
    },
    grid: {
      containLabel: true
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      axisLabel: {
        // rotate: 40,
        fontSize: '15'
      },
      type: 'category',
      name: '日期',
      boundaryGap: false,
      data: x
      // show: false
    },
    yAxis: {
      axisLabel: {
        // rotate: 40,
        fontSize: '15'
      },
      x: 'center',
      type: 'value',
      name: '人数(个)',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
        // show: false
      }
    },
    series: [
      {
        name: '总数',
        type: 'line',
        smooth: true,
        data: y1
      },
      {
        name: '新增',
        type: 'line',
        smooth: true,
        data: y2
      }
    ]
  }
  chart.setOption(option, true)
  return chart
}

//更改折线图和数据明细表格数据的函数，多次用到，所以提取出来
function change_ec_and_data() {
  var atemp = []
  for (var i = 0; i < glodata[0].length; i++) {
    atemp[i] = glodata[0][i].substring(5)
  }
  x = atemp.reverse()
  y1 = glodata[1][0].reverse()
  y2 = glodata[2][0].reverse()
  the_newest = glodata[3].split(' ')[1]
  glo_data_detail = {}
  for (var i = x.length - 1; i >= 0; i--) {
    glo_data_detail[i] = {
      date: x[i],
      all: y1[i],
      new: y2[i]
    }
  }
  if (the_newest != '23:59:59') {
    x = x.slice(1).reverse()
    y1 = y1.slice(1).reverse()
    y2 = y2.slice(1).reverse()
  } else {
    x.reverse()
    y1.reverse()
    y2.reverse()
  }
}

@withWeapp('Page')
class _C extends Taro.Component {
  state = {
    is_allof_china: true, //用于判断当前区域是否为全中国
    currnetType: 'confirmedCount', //当前的种类
    isprovince: false, //用于判断当前区域是否为省级
    area_in_province: '全部', //省内的某个区域，二级导航的选项
    province_area: '中国', //国内的某个区域，一级导航的选项

    //下面是一级导航菜单的数组，其中id用于判断是否为正常的省
    selectArray: [
      { text: '全国', id: 0 },
      { text: '武汉', id: 0 },
      { text: '湖北', id: 1 },
      { text: '浙江', id: 1 },
      { text: '广东', id: 1 },
      { text: '河南', id: 1 },
      { text: '湖南', id: 1 },
      { text: '江西', id: 1 },
      { text: '安徽', id: 1 },
      { text: '重庆', id: 1 },
      { text: '山东', id: 1 },
      { text: '四川', id: 1 },
      { text: '江苏', id: 1 },
      { text: '北京', id: 1 },
      { text: '上海', id: 1 },
      { text: '福建', id: 1 },
      { text: '广西', id: 1 },
      { text: '陕西', id: 1 },
      { text: '云南', id: 1 },
      { text: '河北', id: 1 },
      { text: '黑龙江', id: 1 },
      { text: '海南', id: 1 },
      { text: '辽宁', id: 1 },
      { text: '山西', id: 1 },
      { text: '天津', id: 1 },
      { text: '贵州', id: 1 },
      { text: '甘肃', id: 1 },
      { text: '宁夏', id: 1 },
      { text: '内蒙古', id: 1 },
      { text: '新疆', id: 1 },
      { text: '吉林', id: 1 },
      { text: '香港', id: 0 },
      { text: '台湾', id: 0 },
      { text: '青海', id: 1 },
      { text: '澳门', id: 0 },
      { text: '西藏', id: 1 }
    ],

    tableData: glo_data_detail, //数据明细表格的数组

    citylist: glo_city_list, //某省城市列表的数组

    ec: { onInit: initChart }, //echart的东西。。

    newdata: ''
  }
  onShareAppMessage = res => {
    var that = this
    var sharemessage = {
      area: area, //访问接口函数的地区参数
      type: type, //访问接口函数的种类参数
      one: that.data.province_area, //一级导航
      two: that.data.area_in_province, //二级导航
      is_province: that.data.isprovince, //是否为省份
      is_all: that.data.is_allof_china //是否为全国
    }
    if (sharemessage.one == '中国') {
      sharemessage.one = '全国'
    }
    var adata = JSON.stringify(sharemessage)
    return {
      title: '新冠疫情分析',
      path: '/pages/index/index?id=' + adata,
      success: function() {},
      fail: function() {}
    }
  }

  componentWillMount(options) {
    var that = this
    var tempmessage = { area: '中国', type: 'confirmedCount' } //初始化
    if (Object.keys(options).length != 0) {
      //若为转发分享页面，则进行数据处理
      var atemp = JSON.parse(options.id)
      app.globalData.cur_area = atemp.one
      tempmessage = {
        area: atemp.area,
        type: atemp.type
      }
      that.setData({
        area_in_province: atemp.two,
        is_allof_china: atemp.is_all,
        currentTab: atemp.type,
        isprovince: atemp.is_province
      })
      if (atemp.one == '全国') {
        atemp.one = '中国'
      }
      city_name = { event_name: '2019-nCoV', area_name: atemp.one }
      AV.Cloud.run('get_areas', city_name).then(function(name_list) {
        var a = ['全部']
        var temp_citylist = a.concat(name_list)
        that.setData({
          citylist: temp_citylist
        })
      })
    }
    this.oneComponent = this.selectComponent('#mychart-dom-line')
    paramsJson = {
      event_name: '2019-nCoV',
      area_name: tempmessage.area,
      type_list: [tempmessage.type]
    }
    AV.Cloud.run('get_stat_data', paramsJson).then(function(data_list) {
      glodata = data_list
      change_ec_and_data()
      that.setData({
        tableData: glo_data_detail,
        newdata: the_newest
      })
      that.init_one()
    })
  }

  getData = () => {}
  init_one = () => {
    this.oneComponent.init((canvas, width, height) => {
      chart = echarts.init(canvas, null, {
        width: width,
        height: height
      })
      canvas.setChart(chart)
      chart.setOption(
        {
          title: {
            left: 'right'
          },
          animation: false,
          color: ['#778899', '#37A2DA'],
          legend: {
            data: ['总数', '新增'],
            top: 20,
            right: 20,
            z: 100
          },
          grid: {
            containLabel: true,
            left: '20',
            width: '300'
          },
          tooltip: {
            show: true,
            trigger: 'none'
            // trigger: 'none'
          },
          xAxis: {
            axisLabel: {
              // rotate: 40,
              fontSize: '15'
            },
            type: 'category',
            name: '日期',
            boundaryGap: false,
            data: x
            // show: false
          },
          yAxis: {
            axisLabel: {
              // rotate: 40,
              fontSize: '15'
            },
            x: 'center',
            type: 'value',
            name: '人数(个)',
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
              // show: false
            }
          },
          series: [
            {
              name: '总数',
              type: 'line',
              smooth: true,
              data: y1
            },
            {
              name: '新增',
              type: 'line',
              smooth: true,
              data: y2
            }
          ]
        },
        true
      )
      this.chart = chart
      return chart
    })
  }
  chooseprovince = e => {
    var that = this
    var a = ['全部'] //获取的城市列表需要添加个开头
    var id = e.detail.id
    area = e.detail.text
    if (area == '全国') {
      area = '中国'
    }
    type = 'confirmedCount' //每次切换省份就跳回确诊类型
    city_name = { event_name: '2019-nCoV', area_name: area }
    AV.Cloud.run('get_areas', city_name).then(function(name_list) {
      glo_city_list = a.concat(name_list)
      that.setData({
        citylist: glo_city_list
      })
    })
    paramsJson = { event_name: '2019-nCoV', area_name: area, type_list: [type] }
    AV.Cloud.run('get_stat_data', paramsJson).then(
      function(data_list) {
        glodata = data_list
        change_ec_and_data()
        that.setData({
          tableData: glo_data_detail,
          newdata: the_newest
        })
        that.init_one()
      },
      function(err) {
        x = []
        y1 = []
        y2 = [] //若报错就全弄为空，其实没啥必要
        that.setData({
          tableData: []
        })
        that.init_one()
      }
    )
    //下面这堆与传入数据无关的处理，由于较长放在后面
    if (id == 0) {
      that.setData({
        isprovince: false,
        currnetType: 'confirmedCount',
        province_area: area,
        area_in_province: '全部'
      })
    } else {
      that.setData({
        isprovince: true,
        currnetType: 'confirmedCount',
        province_area: area,
        area_in_province: '全部'
      })
    }
    if (area == '中国') {
      that.setData({
        is_allof_china: true
      })
    } else {
      that.setData({
        is_allof_china: false
      })
    }
  }
  choosetype = e => {
    var that = this
    type = e.target.dataset.id
    area = that.data.area_in_province
    if (area == '全部') {
      area = that.data.province_area
    }
    that.setData({
      currnetType: type
    })
    paramsJson = { event_name: '2019-nCoV', area_name: area, type_list: [type] }
    AV.Cloud.run('get_stat_data', paramsJson).then(
      function(data_list) {
        glodata = data_list
        change_ec_and_data()
        that.setData({
          tableData: glo_data_detail,
          newdata: the_newest
        })
        that.init_one()
      },
      function(err) {
        x = []
        y1 = []
        y2 = [] //若报错就全弄为空，其实没啥必要
        that.setData({
          tableData: []
        })
        that.init_one()
      }
    )
  }
  choosecity = e => {
    var that = this
    area = e.currentTarget.dataset.id
    type = 'confirmedCount' //切换城市后类型变为确诊
    that.setData({
      area_in_province: area,
      currnetType: 'confirmedCount'
    })
    if (area == '全部') {
      area = that.data.province_area
    }
    paramsJson = { event_name: '2019-nCoV', area_name: area, type_list: [type] }
    AV.Cloud.run('get_stat_data', paramsJson).then(
      function(data_list) {
        glodata = data_list
        change_ec_and_data()
        that.setData({
          tableData: glo_data_detail,
          newdata: the_newest
        })
        that.init_one()
      },
      function(err) {
        x = []
        y1 = []
        y2 = [] //若报错就全弄为空，其实没啥必要
        that.setData({
          tableData: []
        })
        that.init_one()
      }
    )
  }
  config = {
    component: true
  }

  render() {
    const {
      selectArray: selectArray,
      area_in_province: area_in_province,
      citylist: citylist,
      isprovince: isprovince,
      currnetType: currnetType,
      is_allof_china: is_allof_china,
      ec: ec,
      tableData: tableData,
      newdata: newdata
    } = this.state
    return (
      <View className="mycontainer">
        <View>
          <Text className="theme">分区了解疫情趋势</Text>
          <View className="current-area">
            <Select
              propArray={selectArray}
              onMyget={this.chooseprovince}
            ></Select>
          </View>
          {isprovince && (
            <View className="city">
              {citylist.map((item, index) => {
                return (
                  <Text
                    className={
                      'city-item ' +
                      (area_in_province == citylist[index] ? 'city_is_on ' : '')
                    }
                    onClick={this.choosecity}
                    data-id={citylist[index]}
                    key="key"
                  >
                    {citylist[index]}
                  </Text>
                )
              })}
            </View>
          )}
          <View className="type">
            <View
              className={
                'type-item ' +
                (currnetType == 'confirmedCount' ? 'type_is_on' : '')
              }
              data-id="confirmedCount"
              onClick={this.choosetype}
            >
              确诊
            </View>
            {is_allof_china && (
              <View
                className={
                  'type-item ' +
                  (currnetType == 'suspectedCount' ? 'type_is_on' : '')
                }
                data-id="suspectedCount"
                onClick={this.choosetype}
              >
                疑似
              </View>
            )}
            {is_allof_china && (
              <View
                className={
                  'type-item ' +
                  (currnetType == 'seriousCount' ? 'type_is_on' : '')
                }
                data-id="seriousCount"
                onClick={this.choosetype}
              >
                重症
              </View>
            )}
            <View
              className={
                'type-item ' + (currnetType == 'curedCount' ? 'type_is_on' : '')
              }
              data-id="curedCount"
              onClick={this.choosetype}
            >
              治愈
            </View>
            <View
              className={
                'type-item ' + (currnetType == 'deadCount' ? 'type_is_on' : '')
              }
              data-id="deadCount"
              onClick={this.choosetype}
            >
              死亡
            </View>
          </View>
        </View>
        {/*  板块二，折线图板块  */}
        <View className="ec-border container">
          {true && (
            <EcCanvas
              id="mychart-dom-line"
              canvasId="mychart-line"
              style="height:500rpx"
              ec={ec}
            ></EcCanvas>
          )}
        </View>
        {/*  板块三，数据明细表格板块  */}
        <View className="data">
          <View className="data-word">数据明细</View>
          <View className="table-border">
            <View className="table-title">
              <View className="table-data">日期</View>
              <View className="table-middle_data">总数</View>
              <View className="table-data">新增</View>
            </View>
            {tableData.map((item, index) => {
              return (
                <View className="table-detail" key="key">
                  <View className="table-data">{tableData[index].date}</View>
                  <View
                    className={
                      'table-middle_data ' +
                      (newdata != '23:59:59' && index == 0 ? 'is_increase' : '')
                    }
                  >
                    {tableData[index].all}
                  </View>
                  <View
                    className={
                      'table-data ' +
                      (newdata != '23:59:59' && index == 0 ? 'is_increase' : '')
                    }
                  >
                    {tableData[index].new}
                  </View>
                </View>
              )
            })}
            <View className="data-origin">数据来自丁香园</View>
          </View>
        </View>
      </View>
    )
  }
}

export default _C
